﻿// Copyright 2009, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Author: api.anash@gmail.com (Anash P. Oommen)

using ExtremeSwank.OpenId;
using ExtremeSwank.OpenId.PlugIns.Discovery;
using ExtremeSwank.OpenId.PlugIns.Extensions;

using System;
using System.Collections.Generic;
using System.Web.UI;

namespace OpenIdDemo {
  /// <summary>
  /// This is a test page that demonstrates the use of openid for google apps.
  /// </summary>
  public partial class IndexPage : Page {

    /// <summary>
    /// Default public constructor.
    /// </summary>
    public IndexPage()
      : base() {
      openid = new OpenIdClient();
      googleXrds = new GoogleAppsDiscovery(openid);
    }

    /// <summary>
    /// The page load handler for this page.
    /// </summary>
    /// <param name="sender">The object sending this event.</param>
    /// <param name="e">Additonal event arguments.</param>
    protected void Page_Load(object sender, EventArgs e) {
      errors.InnerText = "";
      if (!IsPostBack) {
        switch (openid.RequestedMode) {
          case RequestedMode.IdResolution:
            if (openid.ValidateResponse()) {
              OpenIdUser user = openid.RetrieveUser();
              Session["OpenIdUser"] = user;
            } else {
              errors.InnerText = "The claimed id could not be validated.";
            }

            break;
          case RequestedMode.CanceledByUser:
            errors.InnerText = "User cancelled openid login sequence.";
            break;
        }
      }
      FixControls();
    }
    /// <summary>
    /// Event handler for login link.
    /// </summary>
    /// <param name="sender">The object sending this event.</param>
    /// <param name="e">Additonal event arguments.</param>
    protected void LoginButton_Click(object sender, EventArgs e) {
      // Enable Directed Identity.
      openid.UseDirectedIdentity = true;

      // Request email and firstname.
      AttributeExchange ax = new AttributeExchange(openid);
      ax.AddFetchItem(AttributeExchangeSchema.Email, 1, true);
      ax.AddFetchItem(AttributeExchangeSchema.FirstName, 1, true);

      // Set PAPE policy max_age as 0, to force a login dialog every time.
      AuthenticationPolicy papePolicy = new AuthenticationPolicy(openid);
      papePolicy.MaxAge = 0;

      // Fetch the xrds document, and find the openid endpoint from it.
      string providerUrl = "";

      try {
        providerUrl = googleXrds.FetchProviderUrlFromEmail(DomainBox.Text);
        errors.InnerText = "";
      } catch (Exception ex) {
        errors.InnerText = ex.Message;
      }

      if (!string.IsNullOrEmpty(providerUrl)) {
        openid.ProviderUrl = new Uri(providerUrl);
        Uri redirectUrl = openid.CreateRequest(false, false);
        Response.Redirect(redirectUrl.AbsoluteUri);
      }
    }

    /// <summary>
    /// Event handler for logout link.
    /// </summary>
    /// <param name="sender">The object sending this event.</param>
    /// <param name="e">Additonal event arguments.</param>
    protected void LogOutButton_Click(object sender, EventArgs e) {
      Session["OpenIdUser"] = null;
      FixControls();
    }

    /// <summary>
    /// Shows or hides controls based on openid state.
    /// </summary>
    private void FixControls() {
      OpenIdUser user = (OpenIdUser) Session["OpenIdUser"];

      if (user == null) {
        this.loggedin.Visible = false;
        this.loggedout.Visible = true;
      } else {
        this.loggedin.Visible = true;
        this.loggedout.Visible = false;

        this.LoginDetails.Text = string.Format("Hello, {0} ({1}) - Your public id is {2}",
          user.GetValue(AttributeExchangeSchema.FirstName),
          user.GetValue(AttributeExchangeSchema.Email),
          user.Identity);
      }
    }

    /// <summary>
    /// The discovery plugin for google apps.
    /// </summary>
    GoogleAppsDiscovery googleXrds = null;

    /// <summary>
    /// The openid client protocol object.
    /// </summary>
    OpenIdClient openid = null;
  }
}
